// 在 Vue 组件或 JS 文件中
import jwt_decode from 'jwt-decode';
// request.js
const BASE_URL = 'http://localhost:8084/api'; // 替换为你的实际API地址

// 获取存储的token
const getToken = () => {
  return uni.getStorageSync('token') || '';
};
// 解析 Token 的方法
const parseToken = () => {
  try {
    // 1. 获取本地存储的 Token
    const token = uni.getStorageSync('token');
    if (!token) {
      console.error('Token 不存在');
      return;
    }

    // 2. 解码 Token
    const decoded = jwt_decode(token);
    console.log('解码后的 Token 数据:', decoded);

    // 3. 提取 ID（假设 Token 中包含 `id` 字段）
    const userId = decoded.userId;
    console.log('用户 ID:', userId);

    // 其他操作（如存储到 Vuex 或页面数据中）
    return userId;
  } catch (error) {
    console.error('解析 Token 失败:', error);
  }
};
// 设置token
export const setToken = (token) => {
  uni.setStorageSync('token', token);
};

// 清除token
export const clearToken = () => {
  uni.removeStorageSync('token');
};

// 请求拦截器
const request = (options) => {
  return new Promise((resolve, reject) => {
    const token = getToken();
    
    const defaultOptions = {
      url: BASE_URL + options.url,
      method: options.method || 'GET',
      data: options.data,
      header: {
        'Content-Type': 'application/json',
        ...options.header
      }
    };

    // 如果有token，添加到header
    console.log(123, token)
    if (token) {
      defaultOptions.header.Authorization = `Bearer ${token}`;
    }

    uni.request({
      ...defaultOptions,
      success: (res) => {
        // 根据你的API响应结构调整
        if (res.statusCode === 200) {
          resolve(res.data);
        } else if (res.statusCode === 401) {
          // token过期或无效
          clearToken();
          uni.redirectTo({
            url: '/pages/login/login'
          });
          reject(new Error('未授权，请重新登录'));
        } else {
          reject(new Error(res.data.message || '请求失败'));
        }
      },
      fail: (err) => {
        console.log(123456, err)
        uni.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
        reject(err);
      }
    });
  });
};

// 封装常用请求方法
export const http = {
  get: (url, data = {}) => {
    return request({
      url,
      method: 'GET',
      data
    });
  },
  post: (url, data = {}) => {
    return request({
      url,
      method: 'POST',
      data
    });
  },
  put: (url, data = {}) => {
    return request({
      url,
      method: 'PUT',
      data
    });
  },
  delete: (url, data = {}) => {
    return request({
      url,
      method: 'DELETE',
      data
    });
  }
};

// API接口
export const api = {
  parseToken,
  getToken,
  login: (data) => http.post('/login', data),
  register: (data) => http.post('/register', data),
  sendVerificationCode: (email) => http.get('/email/sendCode', { email }),
  getSelectedBooks: () => http.get('/word/getLearnBook'),
  getAllSelectedBooks: () => http.get('/word/getAllLearnBook'),
  saveSelectedBooks: (type) => http.post('/word/saveLearnBook', {type}),
  removeLearnBook: (type) => http.delete("/word/removeLearnBook", {type}),
  getWord: (type) => http.get("/word/get", {type}),
  getWordRandom: () => http.get("/word/getByRandom"),
  getWordByTest: () => http.get("/word/getWordByTest"),
  recordLearningTime: (data) => http.post("/daily/statistics/statisticsTime", data),
  saveWord: (data) => http.post("/learn-word/saveWord", data),
  getDailyStatistics: () => http.get("/daily/statistics/list"),
  getStatisticsByModel: (model) => http.get("/daily/statistics/getStatisticsByModel", {model}),
  getTodayStatistics: () => http.get("/daily/statistics/getByDay"),
  getYesterdayStatistics: () => http.get("/daily/statistics/getByYesterday"),
  // 用户个人信息相关接口
  getUserProfile: () => http.get("/getUserInfo"),
  updateUserProfile: (data) => http.put("/updateUser", data),
  uploadAvatar: (base64Data) => {
    return http.put('/updateUser', { userPhoto: base64Data });
  },
  logout: () => http.post("/logout"),
  getLeaderboard: () => http.get("/learn-word/getLeaderboard"),
  getLevel: () => http.get("/learn-word/getLevel"),
  addDailTask: (data) => http.post("/daily_task/setDailyTaskByDay", data),
  getDailyTaskByDay: () => http.get("/daily_task/getDailyTaskByDay"),
  deleteDailyTask: (data) => http.delete("/daily_task/deleteDailyTask", data),
  getDailyTaskByMonth: () => http.get("/daily_task/getDailyTaskByMonth")
  // 可以继续添加其他API接口
}; 